package com.dragon.app.commons.service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dragon.app.commons.dto.SendSMSDTO;
import com.dragon.app.um.service.ClientUserService;
import com.dragon.common.constant.Constant;
import com.dragon.common.util.PropertiesLoadUtil;
import com.dragon.loan.service.SmsSendCountDragonService;
import com.fintech.common.constant.ErrorCode;
import com.fintech.common.entity.ResultData;
import com.fintech.common.enums.RespStatus;
import com.fintech.common.enums.ReturnCode;
import com.fintech.common.util.RedisUtils;
import com.fintech.common.vo.FintechResult;
import com.fintech.third.constant.ResponseResult;
import com.fintech.third.constant.SmsTypeEnum;
import com.fintech.third.service.sms.SmsService;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

@Service("sMSAppService")
public class SMSServiceImpl implements SMSService {
	private final static int TWELVE_HOUR = 60 *60 * 12;
	
	@Autowired
	private SmsService smsService;
	@Autowired
	private SmsSendCountDragonService smsSendCountDragonService;
	@Autowired
	private ClientUserService clientUserService;
	
	@Override
	public FintechResult ykdRegister( SendSMSDTO sendSMSDTO, String ipAddress){
		MarvelsLogUtil.getInstance().info("public/sms/send====>>"+JSONObject.fromObject(sendSMSDTO));
		FintechResult result = new FintechResult();
		String mobileNo = sendSMSDTO.getMobileNo();
		if(null==sendSMSDTO || StringUtils.isEmpty(mobileNo)){
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage("手机号不存在！");
			return result;
		}
		if(!isMobile(mobileNo)) {
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "请输入正确的手机号");
		}
		// 判断是否准入
		ResultData<Boolean> send = smsSendCountDragonService.isSend(mobileNo, ipAddress);
		if(!send.getData()){
			return FintechResult.getResult(ErrorCode.EXCEPTION, send.getMessage(), null);
		}
		
		// 判断是否是连续两次
		//String smsPicNum = PropertiesLoadUtil.getPropertiesValue("sms.pic.num", "common.properties");
		//Long sendCount = StringUtils.isEmpty(smsPicNum) ? 0L : Long.parseLong(smsPicNum);
		String key = mobileNo + "ykdRegister";
		String key60 = key + "60";
		Long incr60 = RedisUtils.getInstance().incr(key60);
		if(incr60 == 1L) {
			Long incr = RedisUtils.getInstance().incr(key);
			RedisUtils.getInstance().expire(key60, 60);
			if(incr == 1L){
				// 如果是第一次 设置这个可以的过期时间
				RedisUtils.getInstance().expire(key, TWELVE_HOUR);
			}
			// 如果超过发送次数
			/*if(incr > sendCount){
				// 查看redis是否有可验证的图形验证码
				String picCodeKey = mobileNo + "pic";
				String picCode = null;
				// 兼容整合后因为redis反序列化问题
				try {
					picCode = RedisUtils.getInstance().get(picCodeKey);
				} catch (Exception e) {
					RedisUtils.getInstance().del(picCodeKey);
				}
				if(StringUtils.isNotEmpty(picCode)){
					if(!picCode.equalsIgnoreCase(sendSMSDTO.getPicVerifyCode())){
						RedisUtils.getInstance().del(key60);
						return FintechResult.getResult(ErrorCode.PIC_CODE_BAD, "", "验证码错误");
					}
				}else{
					RedisUtils.getInstance().del(key60);
					return FintechResult.getResult(ErrorCode.NEED_PIC_CODE, "", "请输入验证码");
				}
			}*/
		}else if(incr60 > 1L){
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "上一次发送验证码未超过60秒");
		}
		ResponseResult responseResult = smsService.sendSms(mobileNo, null, SmsTypeEnum.REGISTER);
		MarvelsLogUtil.getInstance().info("发送结果##resultMsg>>>>"+JSON.toJSONString(responseResult));
		if ((RespStatus.SUCCESS.getCode() + "").equals(responseResult.getErrorCode())) {
			return FintechResult.getResult(ReturnCode.success.getErrorCode(), ReturnCode.success.getErrorDescribe(), null);
		} else {
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage(responseResult.getMessage());
			return FintechResult.getFailResult(ReturnCode.success.getErrorCode(), responseResult.getMessage());
		}
	}
	
	@Override
	public FintechResult ykdLogin( SendSMSDTO sendSMSDTO, String ipAddress){
		MarvelsLogUtil.getInstance().info("public/sms/send====>>"+JSONObject.fromObject(sendSMSDTO));
		FintechResult result = new FintechResult();
		String mobileNo = sendSMSDTO.getMobileNo();
		if(null==sendSMSDTO || StringUtils.isEmpty(mobileNo)){
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage("手机号不存在！");
			return result;
		}
		if(!isMobile(mobileNo)) {
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "请输入正确的手机号");
		}
		// 判断是否准入
		ResultData<Boolean> send = smsSendCountDragonService.isSend(mobileNo, ipAddress);
		if(!send.getData()){
			return FintechResult.getResult(ErrorCode.EXCEPTION, send.getMessage(), null);
		}
		
		// 判断是否是连续两次
		//String smsPicNum = PropertiesLoadUtil.getPropertiesValue("sms.pic.num", "common.properties");
		//Long sendCount = StringUtils.isEmpty(smsPicNum) ? 0L : Long.parseLong(smsPicNum);
		String key = mobileNo + "ykdLogin";
		String key60 = key + "60";
		Long incr60 = RedisUtils.getInstance().incr(key60);
		if(incr60 == 1L) {
			Long incr = RedisUtils.getInstance().incr(key);
			RedisUtils.getInstance().expire(key60, 60);
			if(incr == 1L){
				// 如果是第一次 设置这个可以的过期时间
				RedisUtils.getInstance().expire(key, TWELVE_HOUR);
			}
			// 如果超过发送次数
			/*if(incr > sendCount){
				// 查看redis是否有可验证的图形验证码
				String picCodeKey = mobileNo + "pic";
				String picCode = null;
				// 兼容整合后因为redis反序列化问题
				try {
					picCode = RedisUtils.getInstance().get(picCodeKey);
				} catch (Exception e) {
					RedisUtils.getInstance().del(picCodeKey);
				}
				if(StringUtils.isNotEmpty(picCode)){
					if(!picCode.equalsIgnoreCase(sendSMSDTO.getPicVerifyCode())){
						RedisUtils.getInstance().del(key60);
						return FintechResult.getResult(ErrorCode.PIC_CODE_BAD, "", "验证码错误");
					}
				}else{
					RedisUtils.getInstance().del(key60);
					return FintechResult.getResult(ErrorCode.NEED_PIC_CODE, "", "请输入验证码");
				}
			}*/
		}else if(incr60 > 1L){
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "上一次发送验证码未超过60秒");
		}
		ResponseResult responseResult = smsService.sendSms(mobileNo, null, SmsTypeEnum.LOGIN);
		MarvelsLogUtil.getInstance().info("发送结果##resultMsg>>>>"+JSON.toJSONString(responseResult));
		if ((RespStatus.SUCCESS.getCode() + "").equals(responseResult.getErrorCode())) {
			return FintechResult.getResult(ReturnCode.success.getErrorCode(), ReturnCode.success.getErrorDescribe(), null);
		} else {
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage(responseResult.getMessage());
			return FintechResult.getFailResult(ReturnCode.success.getErrorCode(), responseResult.getMessage());
		}
	}
	
	
	@Override
	public FintechResult ykdV2Register( SendSMSDTO sendSMSDTO, String ipAddress){
		MarvelsLogUtil.getInstance().info("public/sms/send====>>"+JSONObject.fromObject(sendSMSDTO));
		FintechResult result = new FintechResult();
		String mobileNo = sendSMSDTO.getMobileNo();
		if(null==sendSMSDTO || StringUtils.isEmpty(mobileNo)){
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage("手机号不存在！");
			return result;
		}
		if(!isMobile(mobileNo)) {
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "请输入正确的手机号");
		}
		// 判断是否准入
		ResultData<Boolean> send = smsSendCountDragonService.isSend(mobileNo, ipAddress);
		if(!send.getData()){
			return FintechResult.getResult(ErrorCode.EXCEPTION, send.getMessage(), null);
		}
		
		// 判断是否是连续两次
		String key = mobileNo + "ykdRegister";
		String key60 = key + "60";
		Long incr60 = RedisUtils.getInstance().incr(key60);
		if(incr60 == 1L) {
			Long incr = RedisUtils.getInstance().incr(key);
			RedisUtils.getInstance().expire(key60, 60);
			if(incr == 1L){
				// 如果是第一次 设置这个可以的过期时间
				RedisUtils.getInstance().expire(key, TWELVE_HOUR);
			}
			
			if(!clientUserService.verifySlideCode(sendSMSDTO)){
				return FintechResult.getResult(ErrorCode.EXCEPTION, "", "图形验证码错误");
			}
			
		}else if(incr60 > 1L){
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "上一次发送验证码未超过60秒");
		}
		ResponseResult responseResult = smsService.sendSms(mobileNo, null, SmsTypeEnum.REGISTER);
		MarvelsLogUtil.getInstance().info("发送结果##resultMsg>>>>"+JSON.toJSONString(responseResult));
		if ((RespStatus.SUCCESS.getCode() + "").equals(responseResult.getErrorCode())) {
			return FintechResult.getResult(ReturnCode.success.getErrorCode(), ReturnCode.success.getErrorDescribe(), null);
		} else {
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage(responseResult.getMessage());
			return FintechResult.getFailResult(ReturnCode.success.getErrorCode(), responseResult.getMessage());
		}
	}
	
	@Override
	public FintechResult ykdV2Login( SendSMSDTO sendSMSDTO, String ipAddress){
		MarvelsLogUtil.getInstance().info("public/sms/send====>>"+JSONObject.fromObject(sendSMSDTO));
		FintechResult result = new FintechResult();
		String mobileNo = sendSMSDTO.getMobileNo();
		if(null==sendSMSDTO || StringUtils.isEmpty(mobileNo)){
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage("手机号不存在！");
			return result;
		}
		if(!isMobile(mobileNo)) {
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "请输入正确的手机号");
		}
		// 判断是否准入
		ResultData<Boolean> send = smsSendCountDragonService.isSend(mobileNo, ipAddress);
		if(!send.getData()){
			return FintechResult.getResult(ErrorCode.EXCEPTION, send.getMessage(), null);
		}
		
		// 判断是否是连续两次
		String key = mobileNo + "ykdLogin";
		String key60 = key + "60";
		Long incr60 = RedisUtils.getInstance().incr(key60);
		if(incr60 == 1L) {
			Long incr = RedisUtils.getInstance().incr(key);
			RedisUtils.getInstance().expire(key60, 60);
			if(incr == 1L){
				// 如果是第一次 设置这个可以的过期时间
				RedisUtils.getInstance().expire(key, TWELVE_HOUR);
			}
			
			if(!clientUserService.verifySlideCode(sendSMSDTO)){
				return FintechResult.getResult(ErrorCode.EXCEPTION, "", "图形验证码错误");
			}
			
		}else if(incr60 > 1L){
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "上一次发送验证码未超过60秒");
		}
		ResponseResult responseResult = smsService.sendSms(mobileNo, null, SmsTypeEnum.LOGIN);
		MarvelsLogUtil.getInstance().info("发送结果##resultMsg>>>>"+JSON.toJSONString(responseResult));
		if ((RespStatus.SUCCESS.getCode() + "").equals(responseResult.getErrorCode())) {
			return FintechResult.getResult(ReturnCode.success.getErrorCode(), ReturnCode.success.getErrorDescribe(), null);
		} else {
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage(responseResult.getMessage());
			return FintechResult.getFailResult(ReturnCode.success.getErrorCode(), responseResult.getMessage());
		}
	}
	
	
	@Override
	public FintechResult ykdchangePw( SendSMSDTO sendSMSDTO, String ipAddress){
		MarvelsLogUtil.getInstance().info("public/sms/send====>>"+JSONObject.fromObject(sendSMSDTO));
		FintechResult result = new FintechResult();
		String mobileNo = sendSMSDTO.getMobileNo();
		if(null==sendSMSDTO || StringUtils.isEmpty(mobileNo)){
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage("手机号不存在！");
			return result;
		}
		if(!isMobile(mobileNo)) {
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "请输入正确的手机号");
		}
		// 判断是否准入
		ResultData<Boolean> send = smsSendCountDragonService.isSend(mobileNo, ipAddress);
		if(!send.getData()){
			return FintechResult.getResult(ErrorCode.EXCEPTION, send.getMessage(), null);
		}
		
		// 判断是否是连续两次
		String smsPicNum = PropertiesLoadUtil.getPropertiesValue("sms.pic.num", "common.properties");
		Long sendCount = StringUtils.isEmpty(smsPicNum) ? 0L : Long.parseLong(smsPicNum);
		String key = mobileNo + "ykdchangePw";
		String key60 = key + "60";
		Long incr60 = RedisUtils.getInstance().incr(key60);
		if(incr60 == 1L) {
			Long incr = RedisUtils.getInstance().incr(key);
			RedisUtils.getInstance().expire(key60, 60);
			if(incr == 1L){
				// 如果是第一次 设置这个可以的过期时间
				RedisUtils.getInstance().expire(key, TWELVE_HOUR);
			}
			// 如果超过发送次数
			if(incr > sendCount){
				// 查看redis是否有可验证的图形验证码
				String picCodeKey = mobileNo + "pic";
				String picCode = null;
				// 兼容整合后因为redis反序列化问题
				try {
					picCode = RedisUtils.getInstance().get(picCodeKey);
				} catch (Exception e) {
					RedisUtils.getInstance().del(picCodeKey);
				}
				if(StringUtils.isNotEmpty(picCode)){
					if(!picCode.equalsIgnoreCase(sendSMSDTO.getPicVerifyCode())){
						RedisUtils.getInstance().del(key60);
						return FintechResult.getResult(ErrorCode.PIC_CODE_BAD, "", "验证码错误");
					}
				}else{
					RedisUtils.getInstance().del(key60);
					return FintechResult.getResult(ErrorCode.NEED_PIC_CODE, "", "请输入验证码");
				}
			}
			
		}else if(incr60 > 1L){
			return FintechResult.getResult(ErrorCode.EXCEPTION, "", "上一次发送验证码未超过60秒");
		}
		ResponseResult responseResult = smsService.sendSms(mobileNo, null, SmsTypeEnum.REGISTER);
		MarvelsLogUtil.getInstance().info("发送结果##resultMsg>>>>"+JSON.toJSONString(responseResult));
		if ((RespStatus.SUCCESS.getCode() + "").equals(responseResult.getErrorCode())) {
			return FintechResult.getResult(ReturnCode.success.getErrorCode(), ReturnCode.success.getErrorDescribe(), null);
		} else {
			result.setErrorCode(ReturnCode.fail.getErrorCode());
			result.setMessage(responseResult.getMessage());
			return FintechResult.getFailResult(ReturnCode.success.getErrorCode(), responseResult.getMessage());
		}
	}
	
	public static boolean isMobile(String mobile){
		Pattern p = Pattern.compile(Constant.MOBLE_REG_STR);  
		Matcher m = p.matcher(mobile); 
		return m.matches();
	}
}
